package com.wontube.video.pub;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;

import com.wontube.client.conf.ServerEnvironment;
import com.wontube.client.extension.io.HessianObjectProtocolProxy;
import com.wontube.client.extension.io.JsonObjectProtocolProxy;
import com.wontube.client.extension.io.PHPObjectProtocolProxy;
import com.wontube.client.extension.log.Slf4JLogger;
import com.wontube.client.extension.utils.FileUtils;
import com.wontube.client.io.ProtocolProxyFactory;
import com.wontube.client.log.MinLoggerFactory;
import com.wontube.client.remote.Remoting;


/**
 * 
 * @author LuoBiao(2012-4-5)
 *
 */

public class Loader implements ServletContextListener {
	@Override
	public void contextDestroyed(ServletContextEvent e) {
	}

	@Override
	public void contextInitialized(ServletContextEvent e) {
		// logback日志要用的变量
		String appPath = e.getServletContext().getRealPath("");
		System.setProperty("WEB_HOME", appPath);
		
		String logbackPath = FileUtils.combinePath(appPath, "WEB-INF", "conf", "logback.xml");
		readLogbackConfig(logbackPath);		
		
		MinLoggerFactory.setLogger(new Slf4JLogger());
		
		String serverConfig = FileUtils.combinePath(appPath, "WEB-INF", "conf", "server.json");		
		ServerEnvironment.environment.load(serverConfig);
		
		MinLoggerFactory.setLogger(new Slf4JLogger());
		
		// 监听向服务器的请求
		Remoting.addCreateListener(new RemotingCreateListener());
		
		// 序列化协议
		ProtocolProxyFactory.regist(new JsonObjectProtocolProxy());
		ProtocolProxyFactory.regist(new PHPObjectProtocolProxy());
		ProtocolProxyFactory.regist(new HessianObjectProtocolProxy());
	}
	
	private boolean readLogbackConfig(String logbackPath){
		LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();
		JoranConfigurator configurator = new JoranConfigurator();
		configurator.setContext(lc);
		lc.reset();
		try {
			configurator.doConfigure(logbackPath);
		} catch (JoranException e) {
			return false;
		}
		
		return true;
	}
}
